//
//  YYRegisterViewController.swift
//  STMusic
//
//  Created by stoneobs on 17/4/5.
//  Copyright © 2017年 stoneobs. All rights reserved.
//
//**********************注册***************************
import UIKit

class YYRegisterViewController: STTableViewController,STSendButtonDlegate {

    var sendButton:STSendButton?
    
    var accountTextFiled:UITextField?
    
    var codeTextFiled:UITextField?
    
    
    var pwdTextFiled:UITextField?
    
    
    var registerButton:STButton?
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "注册";
        self.view.backgroundColor = .white;
        self.tableView.backgroundColor = .white;
        self.initSubviews();
        NotificationCenter.default.addObserver(self, selector: #selector(didReciveNotifacationAction(notify:)), name: NSNotification.Name.UITextFieldTextDidChange, object: nil);
        // Do any additional setup after loading the view.
    }

    func didReciveNotifacationAction(notify:NSNotification) -> Void {
        
        if (self.accountTextFiled?.text?.characters.count)! == 11  &&
            (self.codeTextFiled?.text?.characters.count)! >= 3      &&
            (self.pwdTextFiled?.text?.characters.count)! > 5{
            
            self.registerButton?.isUserInteractionEnabled = true;
            self.registerButton?.backgroundColor = UIColor.flatMint;
        }else{
        
            self.registerButton?.isUserInteractionEnabled = false;
            self.registerButton?.backgroundColor = NO_USER_INTERFACE_COLOR;
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self);
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated);

        self.findHairlineImageViewUnder(self.navigationController?.navigationBar).isHidden = true;

       
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated);

        self.findHairlineImageViewUnder(self.navigationController?.navigationBar).isHidden = false;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func initSubviews() -> Void {

        self.accountTextFiled = UITextField.init(frame: .init(x: 25, y: 10, width: SCREEN_WIDTH - 50 - 100, height: 40));
        self.accountTextFiled?.placeholder = "请输入手机号";
        self.accountTextFiled?.keyboardType = .numberPad;
        self.accountTextFiled?.textAlignment = .left;
        self.tableView.addSubview(self.accountTextFiled!);
        
        let accountLine:UIView = UIView.init(frame: CGRect.init(x: 0, y: (self.accountTextFiled?.bottom)!, width: SCREEN_WIDTH - 50, height: 1));
        accountLine.backgroundColor = LINE_COLOR;
         accountLine.centerX = SCREEN_WIDTH / 2;
        self.tableView.addSubview(accountLine);
        
        
        self.codeTextFiled = UITextField.init(frame: .init(x: 25, y: (self.accountTextFiled?.bottom)! + 20, width: SCREEN_WIDTH - 50, height: 40));
        self.codeTextFiled?.placeholder = "请输入验证码";
        self.codeTextFiled?.keyboardType = .numberPad;
        self.codeTextFiled?.centerX = SCREEN_WIDTH / 2;
        self.codeTextFiled?.textAlignment = .left;
        self.tableView.addSubview(self.codeTextFiled!);
        
        let codeLine:UIView = UIView.init(frame: CGRect.init(x: 0, y: (self.codeTextFiled?.bottom)!, width: accountLine.width, height: 1));
        codeLine.backgroundColor = LINE_COLOR;
        codeLine.centerX = SCREEN_WIDTH / 2;
        self.tableView.addSubview(codeLine);
        
        
        self.pwdTextFiled = UITextField.init(frame: .init(x: 25, y: (self.codeTextFiled?.bottom)! + 20, width: SCREEN_WIDTH - 50, height: 40));
        self.pwdTextFiled?.placeholder = "请输入密码6 - 12 位";
        self.pwdTextFiled?.keyboardType = .asciiCapable;
        self.pwdTextFiled?.centerX = SCREEN_WIDTH / 2;
        self.pwdTextFiled?.textAlignment = .left;
        self.pwdTextFiled?.isSecureTextEntry = true;
        self.tableView.addSubview(self.pwdTextFiled!);
        let pwdLine:UIView = UIView.init(frame: CGRect.init(x: 0, y: (self.pwdTextFiled?.bottom)!, width: accountLine.width, height: 1));
        pwdLine.backgroundColor = LINE_COLOR;
        pwdLine.centerX = SCREEN_WIDTH / 2;
        self.tableView.addSubview(pwdLine);
        
        self.sendButton = STSendButton.init(frame: .init(x: 0, y: 0, width: 100, height: 16), andWithDuration: 60);
        self.sendButton?.contentHorizontalAlignment = .right;
        self.sendButton?.centerY = (self.accountTextFiled?.centerY)!;
        self.sendButton?.right = accountLine.right;
        self.sendButton?.delegate = self;
        self.sendButton?.setTitle("获取验证码", for: .normal);
        self.sendButton?.backgroundColor = .clear;
        self.sendButton?.titleLabel?.font = UIFont.systemFont(ofSize: 13);
        self.sendButton?.setTitleColor(ThirdTextColor, for: .normal);
        self.tableView.addSubview(self.sendButton!);
        
        weak var weakSelf = self;
        
        self.registerButton = STButton.init(frame: .init(x: 45, y: (self.pwdTextFiled?.bottom)! + 40, width: SCREEN_WIDTH - 90, height: 40),
                                            title: "立即注册",
                                            titleColor: .white,
                                            titleFont: 15,
                                            cornerRadius: 3,
                                            backgroundColor: NO_USER_INTERFACE_COLOR,
                                            backgroundImage: nil,
                                            image: nil);
        self.registerButton?.isUserInteractionEnabled = false;
        self.registerButton?.centerX = SCREEN_WIDTH / 2;
        self.registerButton?.contentHorizontalAlignment = .center;
        self.registerButton?.clicAction = { but in
        
            weakSelf?.loadRegisterRequest();
        }
        self.tableView.addSubview(self.registerButton!);
        
    }

        //MARK:STSendButtonDlegate
    func stSendButtonShouldBecomeTheFirstResponder(whenWillClicTheSTSend sendButton: UIButton!) -> Bool {
        let myphone:NSString = NSString.init(string: (self.accountTextFiled?.text)!);
        if myphone.length == 0 {
            SVProgressHUD.showError(withStatus: "手机号不能为空");
            
            return false;
        }
        if myphone.length != 11 || !myphone.isPureNumandCharacters() {
            SVProgressHUD.showError(withStatus: "手机号格式不正确");

            return false;
        }
        return true;
        
    }
    func stSendButtonDidClic(_ button: UIButton!, isFirstClic: Bool, duration: Int) {
        if isFirstClic {
            
           self.loadGetCodeRequest(phone: (self.accountTextFiled?.text)!);
        }
    }
    func stSendButtonDidCountdown(_ button: UIButton!, duration: Int) {
        
        self.sendButton?.setTitle("剩余\(duration)秒", for: .normal);
    }
    func stSendButtonTimeEnded(_ button: UIButton!) {
        self.sendButton?.setTitle("重新发送", for: .normal);
        self.sendButton?.timerEnd();
    }
    

        // MARK:Network Request
    func loadGetCodeRequest(phone:String) -> Void {

        BmobSMS.requestCodeInBackground(withPhoneNumber: phone, andTemplate: "余音短信") { (num, error) in
            
            if error == nil{
            SVProgressHUD.showSuccess(withStatus: "短信验证码已发送至" + phone )
               self.sendButton?.timerBegin();
            }else{
                self.sendButton?.timerEnd();
                print("error");
            }
        }
    }
    
    func loadRegisterRequest() -> Void {

        BmobSMS.verifySMSCodeInBackground(withPhoneNumber: self.accountTextFiled?.text, andSMSCode: self.codeTextFiled?.text) { (isSuccess, error) in
            
            if !isSuccess {
            
                SVProgressHUD.showError(withStatus: "短信验证码不正确");
                return;
            }else{
                //注册
                let user = BmobUser();
                user.password = self.pwdTextFiled?.text;
                user.mobilePhoneNumber = self.accountTextFiled?.text;
                user.username = self.accountTextFiled?.text;
                
                user.signUpInBackground({ (isSuccess, signerror) in
                    if isSuccess{
                        SVProgressHUD.dismiss();
                        SVProgressHUD.show(withStatus: "注册成功，正在为您自动登陆");
                        BmobUser.loginWithUsername(inBackground:  user.mobilePhoneNumber , password: user.password, block: { (loginedUser, loginerror) in
                            
                            if (loginerror != nil){
                                SVProgressHUD.showError(withStatus: loginerror?.localizedDescription);
                            
                            }else{
                                let rootVC = STLayoutViewController.defaultLayout();
                                rootVC.leftViewController = STNavigationController.init(rootViewController: YYLeftViewController());
                                rootVC.leftDisplayMode = STLayoutViewDisplayMode.background;
                                rootVC.rightViewController = YYMusciPlayerController.shardPlayer;
                                rootVC.rightDisplayMode = STLayoutViewDisplayMode.cover;
                                //rootVC.setPanGestureEnable(false);
                                self.view.window?.rootViewController = rootVC;
                                SVProgressHUD.dismiss();
                                SVProgressHUD.showSuccess(withStatus: "登录成功");
                                
                            }
                        })
                    }else{
                    
                        SVProgressHUD.dismiss();
                        SVProgressHUD.showError(withStatus: signerror?.localizedDescription);
                    }
                   
                })
            
            }
        }
    }
}
